<?php
// +----------------------------------------------------------------------
// | xiongrui [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.xiongrui.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.xiongrui.cn>
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\common\controller\Admin;
use app\common\model\Goods as GoodsModel;
use app\admin\validate\GoodsValidate;

class Goods extends Admin {
  protected $Goods;
  protected $goodsrule;
  protected $Goodscat;
  public function _initialize() {
		parent::_initialize();
    $this->Goods = model('Goods');
    $this->goodsrule = model('goodsrule');
    $this->Goodscat = model('Goodscat');
	}

  public function index() {

    $cats = $this->Goodscat->where(array('status' => 1, 'goods_type'=>0))->column('id');
    if($cats){
      $map['cat_id'] = array('in', $cats);
    }else{
      $this->error('请先添加分类！');
    }

    $category =   input('get.category');
    if(!empty($category)){
      $map['cat_id'] = $category;
    }

    $map['status']  = 1;
    $this->getGoodListBymap($map);
		$this->setMeta('商品管理');
		return $this->fetch();
	}

  public function getGoodListBymap($map = ''){

    $count = $this->Goods->where($map)->count();
    $list = $this->Goods->where($map)->order('is_timelimit desc,cat_sort asc,update_time desc,id desc')->paginate(100);
    $catlist = $this->Goodscat->order('sort')->where(array('status' => 1))->column('cat_name','id');
    Cookie('__forward__',$_SERVER['REQUEST_URI']);
    $this->assign('catlist', $catlist);
    $this->assign('list', $list);
		$this->assign('count', $count);
  }

    /**
     * 待上架商品——商品库
     */
	public function dsj($keyword = ''){
        $category =   input('get.category');
        if($category){
            $map['cat_id'] = $category;
        }
        if($keyword){
            $map['good_name'] = array('like', '%'.$keyword.'%');
        }
        $map['status']  = array('eq', -1);
        $this->getGoodListBymap($map);
        $this->setMeta('待上架商品');
        return $this->fetch();
    }

    /**
     * 已上架商品
     * @return mixed
     */
    public function ysj($keyword = ''){

        $category =   input('get.category');
        if(!empty($category)){
            $map['cat_id'] = $category;
        }


        if($keyword){
            $map['good_name'] = array('like', '%'.$keyword.'%');
        }
        $map['status']  = 1;
        $this->getGoodListBymap($map);
        $this->setMeta('已上架商品');
        return $this->fetch();
    }

    public function jsps($keyword = '', $modelid = 1, $status = null){

        if($this->request->isPost()){
            $val = '';
            $cats = '';
            if(input('post.goods/a')){
              $val = implode(',', input('post.goods/a'));
            }
            if(input('post.cats/a')){
                $cats = implode(',', input('post.cats/a'));
            }



            model('Goodsmodel')->where('id', $modelid)->update(['goods'=>$val, 'cats'=>$cats]);

            $this->success('导入成功');
        }else{
            $goodsModel = model('Goodsmodel')->where('id', $modelid)->find();
            if(!$goodsModel){
                $this->error('模型不存在');
            }

            $map['id'] = ['in', $goodsModel['goods']];
            $map['status'] = 1;


            $category =   input('get.category');
            if($category){
                $map['cat_id'] = $category;
            }



            if($keyword){
                $map['good_name'] = array('like', '%'.$keyword.'%');
            }


            $this->getGoodListBymap($map);
            $allList = $this->Goods->order('cat_sort asc,update_time desc,id desc')->select();
            $this->assign('allList', $allList);
            $this->assign('goodsIds', $goodsModel['goods']);
            $this->assign('cats', $goodsModel['cats']);
            $this->assign('modelid', $modelid);
            $this->setMeta($goodsModel['name']);
            return $this->fetch();
        }


    }





  public function network() {
    $cats = $this->Goodscat->where(array('status' => 1, 'goods_type'=>1))->column('id');
    if($cats){
      $map['cat_id'] = array('in', $cats);
    }else{
      $this->error('请先添加分类！');
    }

    $category =   input('get.category');
    if(!empty($category)){
      $map['cat_id'] = $category;
    }
    $map['status']  = 1;

		$count = $this->Goods->where($map)->order('id desc')->count();
    $list = $this->Goods->where($map)->order('cat_id desc,sort asc,update_time desc,id desc')->paginate(100);

    $catlist = $this->Goodscat->where(array('status' => 1, 'goods_type'=>1))->column('cat_name','id');
    $this->assign('catlist', $catlist);


    Cookie('__forward__',$_SERVER['REQUEST_URI']);
		$this->assign('list', $list);
		$this->assign('count', $count);

		$this->setMeta('商品管理');
		return $this->fetch('index');
	}
  public function mail() {
    $cats = $this->Goodscat->where(array('status' => 1, 'goods_type'=>2))->column('id');
    if($cats){
      $map['cat_id'] = array('in', $cats);
    }else{
      $this->error('请先添加分类！');
    }
    $category =   input('get.category');
    if(!empty($category)){
      $map['cat_id'] = $category;
    }
    $map['status']  = 1;

		$count = $this->Goods->where($map)->order('id desc')->count();
    $list = $this->Goods->where($map)->order('cat_id desc,sort asc,update_time desc,id desc')->paginate(100);

    $catlist = $this->Goodscat->where(array('status' => 1, 'goods_type'=>2))->column('cat_name','id');
    $this->assign('catlist', $catlist);


    Cookie('__forward__',$_SERVER['REQUEST_URI']);
		$this->assign('list', $list);
		$this->assign('count', $count);
		$this->setMeta('商品管理');
		return $this->fetch('index');
	}
  public function purchasing() {
    $cats = $this->Goodscat->where(array('status' => 1, 'goods_type'=>3))->column('id');
    if($cats){
      $map['cat_id'] = array('in', $cats);
    }else{
      $this->error('请先添加分类！');
    }
    $category =   input('get.category');
    if(!empty($category)){
      $map['cat_id'] = $category;
    }
    $map['status']  = 1;

		$count = $this->Goods->where($map)->order('id desc')->count();
    $list = $this->Goods->where($map)->order('sort asc,update_time desc,id desc')->paginate(20);

    $catlist = $this->Goodscat->where(array('status' => 1, 'goods_type'=>3))->column('cat_name','id');
    $this->assign('catlist', $catlist);


    Cookie('__forward__',$_SERVER['REQUEST_URI']);
		$this->assign('list', $list);
		$this->assign('count', $count);
		$this->setMeta('限购商品');
		return $this->fetch('index');
	}
  public function addindex($keyword=null) {
    if($keyword){
      $map['good_name'] = array('like', '%'.$keyword.'%');
    }
    $map['status']  = array('eq', -1);
    $map['vs_type']  = array('eq', 0);

		$count = $this->Goods->where($map)->order('id desc')->count();
    $list = $this->Goods->where($map)->order('id desc')->paginate(20);

    Cookie('__forward__',$_SERVER['REQUEST_URI']);
		$this->assign('list', $list);
		$this->assign('count', $count);
		$this->setMeta('商品管理');
		return $this->fetch();
	}

	public function add() {
    if (IS_POST) {
        (new GoodsValidate())->goVerify();
      	$result = $this->updateGoods($this->Goods);
      if($result){
        $this->success('添加成功！',  Cookie('__forward__'));
      }else{
        $this->error('添加失败！');
      }
    } else {
      $data = array(
        'info'    => array('good_feature' => 1),
				'fieldGroup' => $this->Goods->addfield(),
			);
			$this->assign($data);
			$this->setMeta("添加商品");
			return $this->fetch('public/edit');
		}
  }

  public function edit($id) {
		if (!$id) {
			return $this->error("非法操作！");
		}
		if (IS_POST) {
        (new GoodsValidate())->goVerify();
      $result = $this->updateGoods($this->Goods, true);
			return $this->success("编辑成功！", Cookie('__forward__'));
		} else {
      $info = $this->Goods->get($id);
      $info->rule = $info->goodsrule()->select();
      $info['timelimit'] = ['is_timelimit'=> $info->is_timelimit,'startlimit'=>$info->startlimit, 'endlimit'=>$info->endlimit];




			$data = array(
				'info'    => $info,
				'fieldGroup' => $this->Goods->addfield(),
			);
			$this->assign($data);
			$this->setMeta('编辑分类');
			return $this->fetch('public/edit');
		}
	}

  public function del($id) {
		if (empty($id)) {
			return $this->error("非法操作！");
		}
		$result = $this->Goods->get($id);
    if($result->delete()){
            // 删除所有的关联数据
          $result->goodsrule()->delete();
          return $this->success("删除成功！");
    }else{
      	return $this->error("删除失败！");
    }

	}

  public function editStatus($id , $status){
    if (empty($id) && empty($status)) {
			return $this->error("非法操作！");
		}
    $result = $this->Goods->where('id',$id)->setField('status', $status);
    if($result){
          return $this->success("修改成功！");
    }else{
      	return $this->error("修改失败！");
    }
  }

  public function copy(){
    $id = $this->getArrayParam('id');
    if (empty($id)) {
			return $this->error("非法操作！");
		}
    session('copyArticle', $id);
    $this->success('请选择要复制到的分类！');

  }


  public function paste() {
      $copyList = session('copyArticle');
      if(empty($copyList)) {
          $this->error('没有选择文档！');
      }
      $cat_id = input('post.cat_id');
      if(!isset($cat_id)) {
          $this->error('请选择要粘贴到的分类！');
      }


      foreach ($copyList as $key=>$value){

          $data   =   $this->Goods->find($value);
          foreach ($data->goodsrule as $key => $value) {
                unset($value['id']);
          }
          unset($data['id']);
          $data->cat_id = $cat_id;
          $goodsdata = $data->toArray();

          $result = GoodsModel::create($goodsdata);
          $result->goodsrule()->saveAll($goodsdata['goodsrule']);
      }
      session('copyArticle', null);
      if($result){
          $this->success('文档复制成功！');
      }else{
          $this->error('文档复制失败！');
      }

  }

  public function pifapaste() {
      $copyList = session('copyArticle');
      if(empty($copyList)) {
          $this->error('没有选择文档！');
      }

      foreach ($copyList as $key=>$value){

          $data   =   $this->Goods->find($value);
          foreach ($data->goodsrule as $key => $value) {
                unset($value['id']);
          }
          unset($data['id']);
          $data->vs_type = 1;
          $data->status = 1;
          $data->yd_type = 0;
          $data->cat_id = 0;
          $goodsdata = $data->toArray();

          $result = GoodsModel::create($goodsdata);
          $result->goodsrule()->saveAll($goodsdata['goodsrule']);
      }
      session('copyArticle', null);
      if($result){
          $this->success('文档复制成功！');
      }else{
          $this->error('文档复制失败！');
      }

  }


  public function sort() {
		if (IS_GET) {
			$ids = input('ids');
			//获取排序的数据
			$map = array('status' => array('gt', -1));
			if (!empty($ids)) {
				$map['id'] = array('in', $ids);
			}

      $category = input('category');
      if (!empty($category)) {
        $map['cat_id'] = $category;
      }
			$list = db('Goods')->where($map)->field('id,good_name')->order('sort asc,update_time desc,id desc')->select();

			$this->assign('list', $list);
			$this->setMeta('排序');
			return $this->fetch();
		} elseif (IS_POST) {
			$ids = input('post.ids');
			$ids = explode(',', $ids);
			foreach ($ids as $key => $value) {
				$res = db('Goods')->where(array('id' => $value))->setField('sort', $key + 1);
			}
			if ($res !== false) {
				return $this->success('排序成功！', Cookie('__forward__'));
			} else {
				return $this->error('排序失败！');
			}
		} else {
			return $this->error('非法请求！');
		}
	}

  /**
   * 批发商品  vs_type 1
   */
   public function indexsub($keyword=null) {
    $map = ['status'=>-1, 'vs_type'=>1, 'yd_type'=>0];
    if($keyword){
     $map['good_name'] = array('like', '%'.$keyword.'%');
    }
    $count = GoodsModel::getCountBymap($map);
    $list  = GoodsModel::getPaginateBymap($map);
    Cookie('__forward__',$_SERVER['REQUEST_URI']);
		$this->assign('list', $list);
		$this->assign('count', $count);
		$this->setMeta('配送商品管理列表');
		return $this->fetch();
 	}
   public function alreadyindexsub($keyword=null) {
    $map = ['status'=>1, 'vs_type'=>1, 'yd_type'=>0];
    if($keyword){
     $map['good_name'] = array('like', '%'.$keyword.'%');
    }
    $count = GoodsModel::getCountBymap($map);
    $list  = GoodsModel::getPaginateBymap($map);
    Cookie('__forward__',$_SERVER['REQUEST_URI']);
		$this->assign('list', $list);
		$this->assign('count', $count);
		$this->setMeta('配送商品管理列表');
		return $this->fetch('indexsub');
 	}
   public function auditindexsub($keyword=null) {
    $map = ['status'=>0, 'vs_type'=>1];
    if($keyword){
     $map['good_name'] = array('like', '%'.$keyword.'%');
    }
    $count = GoodsModel::getCountBymap($map);
    $list  = GoodsModel::getPaginateBymap($map);
    Cookie('__forward__',$_SERVER['REQUEST_URI']);
		$this->assign('list', $list);
		$this->assign('count', $count);
		$this->setMeta('预约商品管理列表');
		return $this->fetch('indexsub');
 	}
  public function addsub($ydtype = 0) {
    if (IS_POST) {
        (new GoodsValidate())->goVerify();
      	$result = $this->updateGoods($this->Goods);
      if($result){
        $this->success('添加成功！',  url('admin/Goods/indexsub'));
      }else{
        $this->error('添加失败！');
      }
    } else {
      $data = array(
        'info'    => array('vs_type' => 1, 'yd_type'=>$ydtype),
				'fieldGroup' => $this->Goods->addsubfield(),
			);
			$this->assign($data);
			$this->setMeta("添加商品");
			return $this->fetch('public/edit');
		}
  }

  public function editsub($id) {
		if (!$id) {
			return $this->error("非法操作！");
		}
		if (IS_POST) {
	    $result = $this->updateGoods($this->Goods, true);
			return $this->success("编辑成功！", Cookie('__forward__'));
		} else {
      $info = $this->Goods->get($id);
      $info->rule = $info->goodsrule()->select();
      $info->yd_sj_time = $info->toArray();

			$data = array(
				'info'    => $info,
				'fieldGroup' => $this->Goods->addsubfield(),
			);
			$this->assign($data);
			$this->setMeta('编辑分类');
			return $this->fetch('public/edit');
		}
	}

  /**
   * 直发商品【待上架】
   * @param  [string] $keyword [搜索关键词]
   * @return [html]          [description]
   */
  public function indexstraight($keyword=null) {
    //yd_type 0:配送 1：直发
    //vs_type 0:普通 1：配送和直发
   $map = ['status'=>-1, 'vs_type'=>1, 'yd_type'=>1];
   if($keyword){
    $map['good_name'] = array('like', '%'.$keyword.'%');
   }

   $count = GoodsModel::getCountBymap($map);
   $list  = GoodsModel::getPaginateBymap($map);
   Cookie('__forward__',$_SERVER['REQUEST_URI']);
   $this->assign('list', $list);
   $this->assign('count', $count);
   $this->setMeta('预约商品管理列表');
   return $this->fetch('indexstraight');
 }
 /**
  * 已上架
  * @param  [type] $keyword [description]
  * @return [type]          [description]
  */
  public function alreadyindexstraight($keyword=null) {
    //yd_type 0:配送 1：直发
    //vs_type 0:普通 1：配送和直发
   $map = ['status'=>1, 'vs_type'=>1, 'yd_type'=>1];
   if($keyword){
    $map['good_name'] = array('like', '%'.$keyword.'%');
   }

   $count = GoodsModel::getCountBymap($map);
   $list  = GoodsModel::getPaginateBymap($map);
   Cookie('__forward__',$_SERVER['REQUEST_URI']);
   $this->assign('list', $list);
   $this->assign('count', $count);
   $this->setMeta('预约商品管理列表');
   return $this->fetch('indexstraight');
 }

 public function othersort($yd_type = 1) {
   if (IS_GET) {
     $ids = input('ids');
     //获取排序的数据
     $map = array('status' => array('gt', -1));
     if (!empty($ids)) {
       $map['id'] = array('in', $ids);
     }

     $map['vs_type'] = 1;
     $map['yd_type'] = $yd_type;

     $list = db('Goods')->where($map)->field('id,good_name')->order('sort asc,update_time desc,id desc')->select();

     $this->assign('list', $list);
     $this->setMeta('排序');
     return $this->fetch('sort');
   } elseif (IS_POST) {
     $ids = input('post.ids');
     $ids = explode(',', $ids);
     foreach ($ids as $key => $value) {
       $res = db('Goods')->where(array('id' => $value))->setField('sort', $key + 1);
     }
     if ($res !== false) {
       return $this->success('排序成功！', Cookie('__forward__'));
     } else {
       return $this->error('排序失败！');
     }
   } else {
     return $this->error('非法请求！');
   }
 }

  public function updateGoods($model, $update = false){
   $result = $model->change();
   if($update){
     $model->goodsrule()->delete();
   }

   $ruledata = array();
   $rule_name =   input('post.rule_name/a');
   $rule_price =   input('post.rule_price/a');
   $rule_price2 =   input('post.rule_price2/a');
   $rule_price3 =   input('post.rule_price3/a');
   $rule_price4 =   input('post.rule_price4/a');
   $stock =   input('post.stock/a');
   $weight =   input('post.weight/a');

   $quota =   input('post.quota/a');

   $pack_price =   input('post.pack_price/a');
   $market_price =   input('post.market_price/a');
   foreach ($rule_name as $key => $value) {
     $ruledata[$key]['rule_name'] = $value;
     $ruledata[$key]['rule_price'] = $rule_price[$key];
     $ruledata[$key]['rule_price2'] = $rule_price2[$key];
     $ruledata[$key]['rule_price3'] = $rule_price3[$key];
     $ruledata[$key]['rule_price4'] = $rule_price4[$key];
     $ruledata[$key]['stock'] = $stock[$key];
     $ruledata[$key]['weight'] = $weight[$key];
     $ruledata[$key]['market_price'] = $market_price[$key];
     $ruledata[$key]['quota'] = $quota[$key];
   }
   $model->goodsrule()->saveAll($ruledata);

   return true;

  }
  /**
   * 修改字段
   * @param  string $id [description]
   * @return [type]     [description]
   */
  public function updateFieldById($id, $field , $value){
    if(empty($id) && empty($field)){
      $this->error('参数错误');
    }

    db('Goods')->where('id', $id)->update(['update_time'=>time(),'sort'=>0]);
    $this->success('刷新成功');
  }


}

 ?>
